package com.MutiModule.common.fileld.validator.referee;

import java.math.BigDecimal;

import com.MutiModule.common.fileld.validator.AbstractCompareReferee;
import com.MutiModule.common.fileld.validator.Rule.NumberRange;
import com.MutiModule.common.fileld.validator.State;

/**
 * 对数字进行范围比较
 * 
 */
public class NumberRangeReferee extends AbstractCompareReferee<NumberRange> {

	@Override
	public State check(Object data) {
		// 进行数字转换
		if (data == null || !(isNumeric(data.toString()))) {
			return failure(getMessageRuleFirst("number.numberRange", String.format("The field is not type of Number.", fieldName)));
		}

		Object maxNumber = rule.max() + "";
		if (!(isNumeric(maxNumber.toString()))) {
			return failure(getMessageRuleFirst("number.numberRange", String.format("The target is not type of Number.", fieldName)));
		}

		Object minNumber = rule.min() + "";
		if (!(isNumeric(minNumber.toString()))) {
			return failure(getMessageRuleFirst("number.numberRange", String.format("The target is not type of Number.", fieldName)));
		}

		BigDecimal number = new BigDecimal(data + "");
		BigDecimal maxNumberBigDceimal = new BigDecimal(maxNumber + "");
		BigDecimal minNumberBigDceimal = new BigDecimal(minNumber + "");

		if (number.doubleValue() < maxNumberBigDceimal.doubleValue() && number.doubleValue() > minNumberBigDceimal.doubleValue()) {
			return simpleSuccess();
		}else if (rule.minEquals() && number.doubleValue() == minNumberBigDceimal.doubleValue()) {
			return simpleSuccess();
		}else if (rule.maxEquals() && number.doubleValue() == maxNumberBigDceimal.doubleValue()) {
			return simpleSuccess();
		}else {
			return failure(getMessageRuleFirst("number.numberRange", "The data is not range the target data"));
		}
	}

	@Override
	public State check(Object data, String serviceLine) {
		String annotationServiceLine = this.rule.serviceLine();
		if (annotationServiceLine != null && !annotationServiceLine.equals("")) {
			if (annotationServiceLine.contains(serviceLine)) {
				return check(data);
			}
		}
		return new State(true, "");
	}

	private static boolean isNumeric(String str) {
		for (int i = 0; i < str.length(); i++) {
			if (!Character.isDigit(str.charAt(i))) {
				return false;
			}
		}
		return true;
	}
}
